package com.qf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.dao.QfCourseClassifyRepository;
import com.qf.dao.QfCourseMapper;
import com.qf.pojo.entity.QfCourse;
import com.qf.pojo.entity.QfCourseClassify;
import com.qf.pojo.req.QfCourseReq;
import com.qf.pojo.resp.BaseResp;
import com.qf.service.QfCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class QfCourseServiceImpl implements QfCourseService {
    @Autowired
    QfCourseMapper qfCourseMapper;
    @Autowired
    QfCourseClassifyRepository qfCourseClassifyRepository;
    @Override
    public BaseResp findAll(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<QfCourse> qfCourseList = qfCourseMapper.findAll();
        PageInfo<QfCourse> qfCoursePageInfo = new PageInfo<>(qfCourseList);
        List<QfCourse> list = qfCoursePageInfo.getList();
        long total = qfCoursePageInfo.getTotal();
        return new BaseResp(1,"success",list,total);
    }

    @Override
    public BaseResp updateOrSave(QfCourseReq qfCourseReq) {
        QfCourseClassify qfCourseClassify = new QfCourseClassify();
        if (qfCourseReq.getId() == null){
            //新增方法
            qfCourseReq.setCreateTime(new Date());
            qfCourseMapper.insertCourse(qfCourseReq);
            //建立课程表和课程分类表之间的联系
            qfCourseClassify.setCourseId(qfCourseReq.getId());
            qfCourseClassify.setClassifyId(qfCourseReq.getQfClassifyId());
        }else{
            //执行修改方法
            qfCourseReq.setUpdateTime(new Date());
            qfCourseMapper.updateCourse(qfCourseReq);
           //通过课程id获取到是否该课程已经建立过课程分类
            qfCourseClassify = qfCourseClassifyRepository.findByCourseId(qfCourseReq.getId());
            //判断 在该课程分类表是否有该课程的分类
            if (qfCourseClassify != null){
                //说明中间表中已经建立了关联关系,这个时候需要对前台传入的分类id进行比对,则代表用户没有修改
                if (qfCourseClassify.getClassifyId() == qfCourseReq.getQfClassifyId()){
                    return new BaseResp().SUCCESS();
                }
                //如果不一致设置新的分类id
                qfCourseClassify.setClassifyId(qfCourseReq.getQfClassifyId());

            }else{
                //建立新的分类即可
                qfCourseClassify = new QfCourseClassify();
                qfCourseClassify.setCourseId(qfCourseReq.getId());
                qfCourseClassify.setClassifyId(qfCourseReq.getQfClassifyId());
            }
        }
        //执行修改或新增的方法
        qfCourseClassifyRepository.saveAndFlush(qfCourseClassify);
        return new BaseResp().SUCCESS();
    }

    /**
     * 删除课程
     * @param id 课程id
     * @return
     */
    @Override
    public BaseResp deleteById(Integer id) {
        qfCourseMapper.deleteById(id);
        qfCourseClassifyRepository.deleteByCourseId(id);
        return new BaseResp().SUCCESS();
    }
}
